'use client';

import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Input } from '@/components/ui/input';

interface PostCount {
  id: number;
  countId: string;
  viewCount: number;
  likeCount: number;
  shareCount: number;
  commentCount: number;
}

interface Category {
  categoryId: number;
  categoryName: string | null;
}

interface User {
  openId: string;
  uName: string;
  avatarUrl: string;
}

interface Post {
  id: string;
  uId: string;
  images: string | null;
  content: string | null;
  categoryId: number | null;
  createTime: string;
  updateTime: string | null;
  status: number;
  user?: User;
  category?: Category | null;
  postCount?: PostCount | null;
}

interface PostDialogProps {
  post: Post | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSave: (post: Post) => void;
  categories: Category[];
}

export function PostDialog({ post, open, onOpenChange, onSave, categories }: PostDialogProps) {
  const [editedPost, setEditedPost] = useState<Post | null>(null);
  const [illegalWordsError, setIllegalWordsError] = useState<string[]>([]);

  useEffect(() => {
    if (post) {
      setEditedPost(post);
      setIllegalWordsError([]);
    }
  }, [post]);

  if (!post || !editedPost) return null;

  const handleSave = async () => {
    try {
      const response = await fetch(`/api/posts?id=${post.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(editedPost),
      });

      const data = await response.json();

      if (!response.ok) {
        if (data.illegalWords) {
          setIllegalWordsError(data.illegalWords);
        }
        throw new Error(data.error || '更新帖子信息失败');
      }

      onSave(data.post);
      onOpenChange(false);
    } catch (error) {
      console.error('更新帖子信息失败:', error);
    }
  };

  const getPostStatusText = (status: number) => {
    switch (status) {
      case 0:
        return '已禁用';
      case 1:
        return '正常';
      case 2:
        return '已置顶';
      default:
        return '未知状态';
    }
  };

  const getPostStatusVariant = (status: number) => {
    switch (status) {
      case 0:
        return 'destructive';
      case 1:
        return 'default';
      case 2:
        return 'success';
      default:
        return 'secondary';
    }
  };

  const formatDate = (dateString: string | null) => {
    if (!dateString) return '未知';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  // 处理图片显示
  const getImageUrls = (images: string | null) => {
    if (!images) return [];
    return images.split(';').filter(url => url.trim() !== '').map(url => {
      // 确保图片URL是完整路径
      if (url.startsWith('http')) {
        return url;
      }
      return `${process.env.NEXT_PUBLIC_BASE_URL || ''}${url}`;
    });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>帖子详情</DialogTitle>
        </DialogHeader>
        <div className="grid gap-4 py-4">
          <div className="grid grid-cols-4 items-center gap-4">
            <label className="text-right">帖子ID</label>
            <div className="col-span-3">
              <span className="text-gray-700">{editedPost.id}</span>
            </div>
          </div>
          
          <div className="grid grid-cols-4 items-center gap-4">
            <label className="text-right">发布者</label>
            <div className="col-span-3 flex items-center space-x-2">
              {editedPost.user && (
                <>
                  <img
                    src={editedPost.user.avatarUrl}
                    alt={editedPost.user.uName}
                    className="h-8 w-8 rounded-full object-cover"
                  />
                  <span>{editedPost.user.uName}</span>
                </>
              )}
            </div>
          </div>
          
          <div className="grid grid-cols-4 items-center gap-4">
            <label className="text-right">分类</label>
            <div className="col-span-3">
              <Select
                value={editedPost.categoryId?.toString() || ''}
                onValueChange={(value) => setEditedPost({ ...editedPost, categoryId: value ? parseInt(value) : null })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择分类" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="none">无分类</SelectItem>
                  {categories.map((category) => (
                    <SelectItem key={category.categoryId} value={category.categoryId.toString()}>
                      {category.categoryName}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
          
          <div className="grid grid-cols-4 items-start gap-4">
            <label className="text-right pt-2">内容</label>
            <div className="col-span-3">
              <Textarea
                value={editedPost.content || ''}
                onChange={(e) => {
                  setEditedPost({ ...editedPost, content: e.target.value });
                  setIllegalWordsError([]);
                }}
                placeholder="帖子内容"
                className="min-h-[100px]"
              />
              <div className="flex items-center space-x-2 mt-1">
                <Button 
                  variant="outline" 
                  size="sm"
                  onClick={async () => {
                    try {
                      const response = await fetch('/api/posts/check-illegal-words', {
                        method: 'POST',
                        headers: {
                          'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({ content: editedPost.content }),
                      });
                      
                      const data = await response.json();
                      
                      if (data.illegalWords && data.illegalWords.length > 0) {
                        let newContent = editedPost.content || '';
                        data.illegalWords.forEach((word: string) => {
                          newContent = newContent.replace(new RegExp(word, 'g'), '***');
                        });
                        
                        setEditedPost({ ...editedPost, content: newContent });
                        setIllegalWordsError(data.illegalWords);
                      } else {
                        setIllegalWordsError([]);
                      }
                    } catch (error) {
                      console.error('检测敏感词失败:', error);
                    }
                  }}
                >
                  检测敏感词
                </Button>
                {illegalWordsError.length > 0 && (
                  <div className="text-red-500 text-sm">
                    <p>内容包含敏感词：{illegalWordsError.join('、')}</p>
                  </div>
                )}
              </div>
            </div>
          </div>
          
          {getImageUrls(editedPost.images).length > 0 && (
            <div className="grid grid-cols-4 items-start gap-4">
              <label className="text-right pt-2">图片</label>
              <div className="col-span-3 grid grid-cols-3 gap-2">
                {getImageUrls(editedPost.images).map((url, index) => (
                  <div key={index} className="relative group">
                    <img
                      src={url}
                      alt={`帖子图片 ${index + 1}`}
                      className="h-20 w-20 object-cover rounded"
                      onError={(e) => {
                        const target = e.target as HTMLImageElement;
                        target.src = '/default-image.png';
                      }}
                    />
                  </div>
                ))}
              </div>
            </div>
          )}
          
          <div className="grid grid-cols-4 items-center gap-4">
            <label className="text-right">发布时间</label>
            <div className="col-span-3">
              <span className="text-gray-700">{formatDate(editedPost.createTime)}</span>
            </div>
          </div>
          
          {editedPost.updateTime && (
            <div className="grid grid-cols-4 items-center gap-4">
              <label className="text-right">更新时间</label>
              <div className="col-span-3">
                <span className="text-gray-700">{formatDate(editedPost.updateTime)}</span>
              </div>
            </div>
          )}
          
          <div className="grid grid-cols-4 items-center gap-4">
            <label className="text-right">状态</label>
            <div className="col-span-3">
              <Select
                value={editedPost.status.toString()}
                onValueChange={(value) => setEditedPost({ ...editedPost, status: parseInt(value) })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="0">已禁用</SelectItem>
                  <SelectItem value="1">正常</SelectItem>
                  <SelectItem value="2">已置顶</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          
          {editedPost.postCount && (
            <div className="grid grid-cols-4 items-center gap-4">
              <label className="text-right">统计数据</label>
              <div className="col-span-3 flex space-x-4">
                <div>
                  <span className="text-sm text-gray-500">浏览</span>
                  <p className="font-medium">{editedPost.postCount.viewCount}</p>
                </div>
                <div>
                  <span className="text-sm text-gray-500">点赞</span>
                  <p className="font-medium">{editedPost.postCount.likeCount}</p>
                </div>
                <div>
                  <span className="text-sm text-gray-500">分享</span>
                  <p className="font-medium">{editedPost.postCount.shareCount}</p>
                </div>
                <div>
                  <span className="text-sm text-gray-500">评论</span>
                  <p className="font-medium">{editedPost.postCount.commentCount}</p>
                </div>
              </div>
            </div>
          )}
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>取消</Button>
          <Button onClick={handleSave}>保存</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}